package com.basin.common.rabbitmq.support;

import com.basin.common.rabbitmq.enums.ExchangeTypeEnum;
import com.basin.common.rabbitmq.property.RabbitMqBindingConfig;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.stereotype.Component;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Component
public class RabbitMqDynamicConfigService {

    @Resource
    private RabbitAdmin rabbitAdmin;

    public void create(RabbitMqBindingConfig config) {
        Queue queue = new Queue(config.getQueueName(), true);
        rabbitAdmin.declareQueue(queue);
        ExchangeTypeEnum exchangeTypeEnum = config.getExchangeTypeEnum();

        // jdk12预览版功能 -> jdk14正式版功能
        switch (exchangeTypeEnum) {
            case TOPIC -> {
                TopicExchange exchange = new TopicExchange(config.getExchangeName());
                rabbitAdmin.declareExchange(exchange);
                rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(config.getRoutingKey()));
            }
            case DIRECT -> {
                DirectExchange exchange = new DirectExchange(config.getExchangeName());
                rabbitAdmin.declareExchange(exchange);
                rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(config.getRoutingKey()));
            }
            case FANOUT -> {
                FanoutExchange exchange = new FanoutExchange(config.getExchangeName());
                rabbitAdmin.declareExchange(exchange);
                rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange));
            }
        }
    }
}
